<template>
  <div class="upload-page">
    <div class="upload-container">
      <h2>纸质表单录入</h2>

      <div
        class="upload-area"
        @click="handleClick"
        @dragover.prevent
        @drop.prevent="handleDrop"
      >
        <input
          type="file"
          ref="fileInput"
          multiple
          accept="image/*"
          style="display: none;"
          @change="handleFileChange"
        >
        <div class="upload-icon">📁</div>
        <p>点击上传或将文件拖拽到这里</p>
        <p class="upload-hint">支持 JPG、PNG 格式文件</p>
        <!-- 新增提示信息 -->
        <p class="upload-tip">💡 建议上传清晰的纸质文档照片</p>
      </div>

      <div class="file-list" v-if="selectedFiles.length > 0">
        <h3>待上传文件 ({{ selectedFiles.length }} 个)</h3>
        <div class="file-item" v-for="(file, index) in selectedFiles" :key="index">
          <span class="file-name">{{ file.name }}</span>
          <span class="file-size">{{ formatFileSize(file.size) }}</span>
          <button class="remove-btn" @click="removeFile(index)">删除</button>
        </div>
        <!-- 新增文件统计 -->
        <div class="file-stats">
          总计: {{ selectedFiles.length }} 个文件,
          总大小: {{ formatFileSize(totalFileSize) }}
        </div>
      </div>

      <button
        class="upload-button"
        @click="confirmUpload"
        :disabled="selectedFiles.length === 0"
        :class="{ uploading: uploading }"
      >
        {{ uploading ? '上传中...' : '确认上传' }}
      </button>

      <div class="upload-history" v-if="uploadHistory.length > 0">
        <div class="history-header">
          <h3>上传历史 (最近10条)</h3>
        </div>
        <div class="history-item" v-for="(item, index) in uploadHistory" :key="index">
          <div class="history-info">
            <span class="filename">{{ item.filename }}</span>
            <span class="time">{{ item.upload_time }}</span>
            <span class="status" :class="getStatusClass(item.status)">{{ item.status }}</span>
            <!-- 新增保存按钮 -->
            <button
              v-if="item.id && item.status.includes('处理完成')"
              class="save-btn"
              @click="saveScannedImage(item.id)"
            >
              保存扫描图
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Upload',
  data() {
    return {
      selectedFiles: [],
      uploadHistory: [],
      uploading: false
    }
  },
  computed: {
    totalFileSize() {
      return this.selectedFiles.reduce((total, file) => total + file.size, 0)
    }
  },
  methods: {
    handleClick() {
      this.$refs.fileInput.click()
    },
    handleDrop(e) {
      const files = Array.from(e.dataTransfer.files)
      this.addFiles(files)
    },
    handleFileChange(e) {
      const files = Array.from(e.target.files)
      this.addFiles(files)
    },
    addFiles(files) {
      files.forEach(file => {
        if (file.type.startsWith('image/')) {
          this.selectedFiles.push(file)
        }
      })
    },
    removeFile(index) {
      this.selectedFiles.splice(index, 1)
    },
    formatFileSize(bytes) {
      if (bytes === 0) return '0 Bytes'
      const k = 1024
      const sizes = ['Bytes', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    },
    async confirmUpload() {
      if (this.selectedFiles.length === 0) return

      this.uploading = true

      const formData = new FormData()
      this.selectedFiles.forEach(file => {
        formData.append('file', file)
      })

      try {
        console.log('开始上传文件...')
        const response = await fetch('http://localhost:5000/upload', {
          method: 'POST',
          body: formData
        })

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`)
        }

        const data = await response.json()
        console.log('上传响应:', data)

        // 将新结果添加到历史记录的开头
        this.uploadHistory = [...data.results, ...this.uploadHistory]
        this.selectedFiles = []

        // 统计成功和失败的数量
        const successCount = data.results.filter(item => item.status.includes('处理完成')).length
        const failCount = data.results.length - successCount

        alert(`上传完成！成功: ${successCount} 个，失败: ${failCount} 个`)

      } catch (error) {
        console.error('上传失败:', error)
        alert(`上传失败: ${error.message}`)
      } finally {
        this.uploading = false
      }
    },
    async saveScannedImage(imageId) {
      try {
        const response = await fetch(`http://localhost:5000/save-scanned/${imageId}`, {
          method: 'POST'
        })

        const data = await response.json()
        if (data.success) {
          alert(data.message)
        } else {
          alert(`保存失败: ${data.error}`)
        }
      } catch (error) {
        console.error('保存失败:', error)
        alert('保存失败，请重试')
      }
    },
    getStatusClass(status) {
      if (status.includes('处理完成')) return 'success'
      if (status.includes('处理中')) return 'warning'
      if (status.includes('处理失败')) return 'error'
      return ''
    }
  }
}
</script>

<style scoped>
.upload-page {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: calc(100vh - 80px);
}

.upload-container {
  max-width: 1200px; /* 增大容器宽度 */
  margin: 0 auto;
  background: white;
  padding: 40px; /* 增大内边距 */
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.upload-area {
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  padding: 80px 40px; /* 增大上传区域 */
  text-align: center;
  cursor: pointer;
  transition: border-color 0.3s ease;
  margin-bottom: 30px;
  background-color: #fafafa; /* 添加背景色 */
}

.upload-area:hover {
  border-color: #409eff;
  background-color: #f0f8ff; /* 悬停时的背景色 */
}

.upload-icon {
  font-size: 64px; /* 增大图标 */
  margin-bottom: 20px;
  color: #409eff;
}

.upload-hint {
  color: #909399;
  font-size: 16px; /* 增大字体 */
  margin-bottom: 10px;
}

.upload-tip {
  color: #67c23a;
  font-size: 14px;
  font-style: italic;
}

.file-list {
  margin-bottom: 30px;
}

.file-list h3 {
  margin-bottom: 15px;
  color: #333;
}

.file-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px; /* 增大内边距 */
  background-color: #fafafa;
  border-radius: 6px; /* 增大圆角 */
  margin-bottom: 10px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.file-name {
  flex: 1;
  color: #333;
  font-size: 14px;
  word-break: break-all; /* 长文件名换行 */
}

.file-size {
  color: #909399;
  margin: 0 20px;
  font-size: 13px;
  min-width: 80px;
  text-align: right;
}

.remove-btn {
  background-color: #f56c6c;
  color: white;
  border: none;
  padding: 6px 15px; /* 增大按钮 */
  border-radius: 4px;
  cursor: pointer;
  font-size: 13px;
}

.remove-btn:hover {
  background-color: #f78989;
}

.file-stats {
  text-align: right;
  padding: 10px 0;
  color: #666;
  font-size: 14px;
  font-weight: 500;
}

.upload-button {
  width: 100%;
  padding: 16px; /* 增大按钮 */
  font-size: 18px; /* 增大字体 */
  margin-bottom: 30px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 6px; /* 增大圆角 */
  cursor: pointer;
  font-weight: 500;
  transition: background-color 0.3s ease;
}

.upload-button:disabled {
  background-color: #a0cfff;
  cursor: not-allowed;
}

.upload-button.uploading {
  background-color: #a0cfff;
}

.upload-button:hover:not(:disabled) {
  background-color: #66b1ff;
}

.upload-history h3 {
  margin-bottom: 15px;
  color: #333;
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.history-item {
  padding: 15px 20px; /* 增大内边距 */
  background-color: #fafafa;
  border-radius: 6px; /* 增大圆角 */
  margin-bottom: 12px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.history-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap; /* 允许换行 */
  gap: 10px;
}

.filename {
  flex: 1;
  font-weight: 500;
  min-width: 150px;
  word-break: break-all;
}

.time {
  color: #909399;
  margin-right: 16px;
  font-size: 13px;
  min-width: 140px;
}

.status {
  padding: 4px 10px; /* 增大内边距 */
  border-radius: 4px;
  font-size: 13px; /* 增大字体 */
  white-space: nowrap;
}

.status.success {
  background-color: #f0f9eb;
  color: #67c23a;
}

.status.warning {
  background-color: #fdf6ec;
  color: #e6a23c;
}

.status.error {
  background-color: #fef0f0;
  color: #f56c6c;
}

.save-btn {
  background-color: #909399;
  color: white;
  border: none;
  padding: 4px 10px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  white-space: nowrap;
}

.save-btn:hover {
  background-color: #a6a9ad;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .upload-container {
    padding: 20px;
    margin: 10px;
  }

  .upload-area {
    padding: 40px 20px;
  }

  .history-info {
    flex-direction: column;
    align-items: flex-start;
  }

  .filename, .time {
    min-width: auto;
    margin-right: 0;
  }
}
</style>